//
//  StationDetailViewController.m
//  Runone
//
//  Created by runone01 on 16/8/5.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "StationDetailViewController.h"
#import "requestStation.h"
#import "Define.h"
#import "AppLocalManager.h"
#import "StationDetailInfo.h"
#import "MJExtension.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "RequestHelper.h"
#import "StationModel.h"
#import "AppDelegate.h"
#import "KGGamePlaySpecailLoopScrollView.h"
#import "BigMapViewController.h"
#import "SVProgressHUD.h"

@interface StationDetailViewController ()<MAMapViewDelegate,UIScrollViewDelegate,UIPopoverPresentationControllerDelegate>
@property(nonatomic,strong)NSMutableArray *imageArray;
@property (nonatomic, strong) MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *buttonView;

@property (weak, nonatomic) IBOutlet UIScrollView *Scrollview;
@property (weak, nonatomic) IBOutlet UIView *ScaleView;

@property (nonatomic, strong)NSTimer *timer;

@property (weak, nonatomic) IBOutlet UIView *StationView;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UIButton *beforeBtn;
@property(nonatomic,strong)StationDetailInfo *stationModel;
@property(nonatomic,strong)NSMutableArray *imagesArray;
@property(nonatomic,strong)UIPageControl *pageC;
@property(nonatomic,strong)BigMapViewController *bigVC;
@property(nonatomic,strong)NSMutableArray *pointarray;
@property(nonatomic)float la,lo;
@property(nonatomic,strong)MAPointAnnotation *pointAnnotation;
//@property(nonatomic,strong)KGGamePlaySpecailLoopScrollView *bannerView;
@end

@implementation StationDetailViewController{
    KGGamePlaySpecailLoopScrollView *bannerView;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=NO;
}

//获取scrollview的宽高不对
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"收费站详情";
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"收费站详情";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    _pointarray=[[NSMutableArray alloc] init];
    _la=0.8;
    _lo=0.9;
    _bigVC=[[BigMapViewController alloc] init];
    CGSize size = CGSizeZero;
    size.width = [UIScreen mainScreen].bounds.size.width;;
    size.height=self.Scrollview.frame.size.height;
    [self requestServer];
    [self loadMapView];
    self.pageC=[[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-30, self.view.frame.size.height/2+350, 30, 30)];
    self.pageC.backgroundColor=[UIColor clearColor];
    self.pageC.numberOfPages=2;
    self.pageC.currentPage=0;
    [self.pageC addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    self.Scrollview.pagingEnabled=YES;
    self.Scrollview.delegate=self;
    bannerView = [[KGGamePlaySpecailLoopScrollView alloc] initWithFrame:CGRectMake(0, 0, size.width, self.Scrollview.frame.size.height-10) animationDuration:3];
    [self.Scrollview addSubview:bannerView];
    //    [self.view addSubview:self.pageC];
    
}
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}
-(void)datePick
{
    _bigVC.modalPresentationStyle=UIModalPresentationPopover;
    
    _bigVC.popoverPresentationController.sourceView=self.view;
    _bigVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x, self.view.center.y, 0, 0);
    _bigVC.popoverPresentationController.permittedArrowDirections=NO;
    _bigVC.popoverPresentationController.delegate=self;
}


-(void)requestServer {
    [self buttonState];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        RequestHelper *requestHelper=[[RequestHelper alloc] init];
        RequestGinsengModel *getHighwayModel=[[RequestGinsengModel alloc] init];
        getHighwayModel.URL=GetDeviceDataURL;
        getHighwayModel.DataValue=[self DataValueStr];
        getHighwayModel.UpdatedTime=@"2000-1-1 12:00:00";
        getHighwayModel.SystemCode=DefaultSystemCode;
        getHighwayModel.MethodName=@"GetTollStationDetailInfo";
        requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
            self.stationModel= dataValueModel;
            
            self.bigVC.stationModel=dataValueModel;
            _bigVC.latitude=_stationModel.Latitude;
            _bigVC.longitude=_stationModel.Longitude;
            _bigVC.Name=[NSString stringWithFormat:@"%@",_stationModel.TollStationName];
            
            self.stationLabel.text=self.stationModel.TollStationName;
            self.pireLabel.text = [NSString stringWithFormat:@"桩号：%@+%ld",self.stationModel.PileNo,(long)self.stationModel.PileDistance];
            self.personName.text=self.stationModel.DutyPersonName;
            _numberPhone.text=_stationModel.MobilePhone;
            self.enterCountLabel.text=[NSString stringWithFormat:@"%ld",(long)self.stationModel.EntranceLaneCount];
             self.outCount.text=[NSString stringWithFormat:@"%ld",(long)self.stationModel.ExitLaneCount];
            self.ETCOutNumber.text=[NSString stringWithFormat:@"%ld",(long)self.stationModel.ETCExitCount];
            self.ETCCountLabel.text=[NSString stringWithFormat:@"%ld",(long)self.stationModel.ETCEntranceCount];
            
            NSMutableArray *arr=[[NSMutableArray alloc] init];
            NSMutableArray *arrStr = [[NSMutableArray alloc] init];
            for (NSString *obj in self.stationModel.TollStationPictures) {
                [arrStr addObject:[self encodeString:obj]];
            }
            [arr addObject:arrStr];
#pragma mark --滚动图片
            //滚动图片
            self.Scrollview.contentSize=CGSizeMake(self.Scrollview.frame.size.width*(arr.count+1), self.Scrollview.frame.size.height);
            [bannerView setGalleryDataSource:arr[0]];
            bannerView.TapActionBlock = ^(NSInteger index){
                //点击图片事件
            };
            bannerView.ChangePageBlock = ^(NSInteger index){
                //图片切换事件
            };
        };
        [requestHelper RequestGinsengModel:getHighwayModel andPushController:self];
    });
}
- (IBAction)big:(UIButton *)sender {
    //[self datePick];
    _bigVC.type=@"收费站";
    [self.navigationController pushViewController:_bigVC animated:YES];
//    [self presentViewController:_bigVC animated:YES completion:nil];
}
- (IBAction)bigbig:(UIButton *)sender {
    sender.selected=!sender.selected;
    if (sender.selected) {
        _mapView.showTraffic=YES;
        [sender setBackgroundImage:[UIImage imageNamed:@"路况"] forState:UIControlStateNormal];
    } else {
        _mapView.showTraffic=NO;
        [sender setBackgroundImage:[UIImage imageNamed:@"路况图标1"] forState:UIControlStateNormal];
    }
    
}

- (IBAction)changePage:(id)sender {
    NSInteger page = self.pageC.currentPage;
    [self.Scrollview setContentOffset:CGPointMake(self.Scrollview.frame.size.width * page, 0)];
}

-(void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.StationView.frame.size.height)];
    _mapView.delegate = self;
    
    _mapView.showsCompass = NO;
    _mapView.showsScale= NO;
    
    [self.StationView addSubview:_mapView];
    [self.StationView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        // annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.image = [UIImage imageNamed:@"收费站图标@3x.png"];
        annotationView.centerOffset = CGPointMake(0, -18);
//        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
//        //  annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
//        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}

-(void)loadAnnotationView {
    [_pointarray removeAllObjects];
    [_mapView removeAnnotation:_pointAnnotation];
    _pointAnnotation = [[MAPointAnnotation alloc] init];
    NSLog(@"%f,%f",_stationModel.Latitude,_stationModel.Longitude);
    float latitude = self.stationModel.Latitude ;
    float longitude = self.stationModel.Longitude ;
    CLLocationCoordinate2D ret = AMapCoordinateConvert(CLLocationCoordinate2DMake(latitude, longitude), AMapCoordinateTypeGPS);
    _pointAnnotation.coordinate=CLLocationCoordinate2DMake(ret.latitude,ret.longitude);
    _pointAnnotation.title = [NSString stringWithFormat:@"%@",self.stationModel.TollStationName];
    _pointAnnotation.subtitle = [NSString stringWithFormat:@"%@",self.stationModel.TollStationName];
    [_mapView addAnnotation:_pointAnnotation];
    [_pointarray addObject:_pointAnnotation];
    [self.mapView showAnnotations:_pointarray edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
}

-(NSString *)DataValueStr
{
    NSString *beginstr=@"[{\"key\":\"TollStationUID\",\"value\":\"";
    NSString *str=self.stationUID;
    NSString *endstr=@"\"}]";
    NSString *temp=[beginstr stringByAppendingString:str];
    NSString *dataValue=[temp stringByAppendingString:endstr];
    return dataValue;
}



-(void)viewDidAppear:(BOOL)animated
{
    [self loadAnnotationView];
    
}
-(void)buttonState{
    self.nextBtn.hidden = NO;
    self.beforeBtn.hidden = NO;
    
    NSArray *dataSourceArray=self.allStationArray;
    
    if(self.selectIndex>=dataSourceArray.count-2)
    {
        self.selectIndex=dataSourceArray.count-2;
        self.nextBtn.hidden = YES;
    }
    
    if(self.selectIndex<=1)
    {
        self.selectIndex=1;
        self.beforeBtn.hidden = YES;
    }
    
    if(self.selectIndex<dataSourceArray.count-2)
    {
        StationDetailInfo *model = dataSourceArray[self.selectIndex+1];
        [self.nextBtn setTitle:model.TollStationName forState:UIControlStateNormal];
        NSLog(@"%@",model.TollStationName);
    }
    
    if(self.selectIndex>1)
    {
        StationDetailInfo *model = dataSourceArray[self.selectIndex-1];
        [self.beforeBtn setTitle:model.TollStationName forState:UIControlStateNormal];
        NSLog(@"%@",model.TollStationName);
    }
    _stationModel = self.allStationArray[self.selectIndex];
   // StationModel *model = self.allStationArray[self.selectIndex];
    self.stationUID = _stationModel.TollStationUID;
    NSLog(@"%@,%f,%f",_stationModel.TollStationName,_stationModel.Latitude,_stationModel.Longitude);
    [self loadAnnotationView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
- (IBAction)rightBtn:(UIButton *)sender {
    [_mapView removeAnnotations:_pointarray];
    [_pointarray removeAllObjects];
    self.selectIndex +=1;
    [self requestServer];
}

- (IBAction)leftBtn:(UIButton *)sender {
    [_mapView removeAnnotations:_pointarray];
    [_pointarray removeAllObjects];
    self.selectIndex -=1;
    [self requestServer];
}

- (void)setCellData:(id)data{
    NSString *path = data;
    NSString *url = [self componentsSeparatedByString:path];
    [self.gcImageView sd_setImageWithURL:[NSURL URLWithString:url]];
}

- (NSString *)componentsSeparatedByString:(NSString *)path{
    NSArray *result = [path componentsSeparatedByString:@"\\"];
    path = nil;
    for (NSString *obj in result) {
        if (path==nil) {
            path = obj;
        }else{
            path = [NSString stringWithFormat:@"%@/%@",path,obj];
        }
    }
    return path;
}

-(NSString *)encodeString:(NSString *)string
{
    NSString *temp = [[NSString stringWithFormat:@"%@",string] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return temp;
}
- (IBAction)enlargeBtnClick:(id)sender {
}
- (IBAction)TrafficBtnClick:(id)sender {
}

- (void)dealloc{
    
}
@end
